$(function(){
	$("#flight-log-form").dialog({width: 600});
	
	$("#openFlightLogs").click(function(){
		$("#flight-log-form").dialog("open");
	});
	
	$.ajax({
		type: "GET",
		url: "http://localhost:8080/getAllFlights",
		dataType: "xml",
		success: function(xml) {
			$("#flight-log-form tr:not(.head)").remove();
			$("#flight-log-form p").remove();
			if ($(xml).find("error").text()!="false")
			{
				errorDesc = $(xml).find("reason").text();
				$("#flight-log-form").append("<p>Error: "+errorDesc+"</p>");
			}
			if ($(xml).find("flight").length>0)
			{
				$(xml).find("flight").each(function(){
					var td,num;
					num = $(this).find("number").text();
					td  = "<tr name=\""+num+"\">\n";
					td += "<td>"+num+"</td>\n";
					td += "<td>"+$(this).find("time").text()+"</td>\n";
					td += "<td>"+$(this).find("durration").text()+"</td>\n";
					td += "<td><button class=\"export_kml\"><span class=\"ui-icon ui-icon-disk\"></span></button></td>\n";
					td += "<td><button class=\"export_csv\"><span class=\"ui-icon ui-icon-script\"></span></button></td>\n";
					td += "<td><button class=\"rm_log\"><span class=\"ui-icon ui-icon-trash\"></span></button></td>\n";
					td += "</tr>\n";
					$("#flight-log-form table").append(td);
				});
				$("button").button();//make them buttons again
			}
			else
			{
				$("#flight-log-form").append("<p>No logs yet...</p>");
			}
		}
	});
	
	$(".export_kml").live('click',function(){
		var flightnum = $(this).closest("tr").attr("name");
		$.get("http://localhost:8080/getKML?flight="+flightnum);
	});
	
	$(".export_csv").live('click',function(){
		var flightnum = $(this).closest("tr").attr("name");
		$.get("http://localhost:8080/getCSV?flight="+flightnum);
	});
	
	$(".rm_log").live('click',function(){
		var flightnum = $(this).closest("tr").attr("name");
		$.get("http://localhost:8080/delLog?flight="+flightnum);
		$(this).closest("tr").remove();
	});
});
